#include "MarkMsg.h"

#include <windows.h>
#include <assert.h>
#include <stdio.h>

struct MarkMsg{
	FILE* pf;
};


// return NULL if failure
struct MarkMsg* MarkMsg_Init(const char* filename) {
	static char* fmt = ".\\%s";
	char buf[MAX_PATH];
	
	// temp use
	struct MarkMsg* obj;
	FILE* pf;

	assert(filename);

	sprintf(buf, fmt, filename);
	pf = fopen(buf, "ab");
	if (pf == NULL) {
		return NULL;
	}

	obj = calloc(1, sizeof(struct MarkMsg));
	if (obj == NULL) {
		fclose(pf);
		return NULL;
	}

	obj->pf = pf;
	return obj;
}

void MarkMsg_Release(struct MarkMsg* obj) {
	if (obj == NULL) {
		return;
	} else {
		fclose(obj->pf);
		free(obj);
	}
}

void _MarkMsg_Now(struct MarkMsg* obj , const unsigned int code, const char* msg, const char* szFile, unsigned int uLine) {
	char buf[1024];
	char mark_time[128];
	SYSTEMTIME st;

	assert(obj);
	GetLocalTime(&st);
	sprintf(mark_time, "%.2hd-%.2hd-%.2hd %.2hd:%.2hd:%.2hd:%.3hd",
			st.wYear, st.wMonth, st.wDay,
			st.wHour, st.wMinute, st.wSecond, st.wMilliseconds);
	sprintf(buf, "Time: %s,  Thread ID: %20u,  File: %s,  Line: %20u,  Code: %20u,  Msg: \"%s\".\r\n", mark_time, GetCurrentThreadId(), szFile, uLine, code, msg);
	printf(buf);
	fprintf(obj->pf, buf);
}
